<!-- 客户管理 -->
<template>
  <div class="app-container">
    <template v-if="showPage">
      <div class="search-bar">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <!--          <el-form-item prop="keyword" label="关键字">-->
          <!--            <el-input-->
          <!--              v-model="queryParams.keyword"-->
          <!--              placeholder="请输入小区名"-->
          <!--              clearable-->
          <!--              @keyup.enter="handleQuery"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item prop="neighborhood" label="小区名称">
            <el-input
              v-model="queryParams.neighborhood"
              placeholder="请输入小区名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item v-if="queryParams.status == 3" prop="ownName" label="业主名称">
            <el-input
              v-model="queryParams.ownName"
              placeholder="请输入业主名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item v-if="queryParams.status == 3" prop="mobile" label="联系电话">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入业主联系电话"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item v-if="queryParams.status == 4" prop="dateRange" label="创建时间">
            <el-date-picker
              v-model="tempTime"
              :editable="false"
              type="datetimerange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item v-if="queryParams.status == 4" label="预算(元)" prop="name">
            <el-input
              v-model="queryParams.budgetMin"
              placeholder="最少预算"
              type="number"
              style="width: 120px"
            />
            <span style="margin: 0 10px">-</span>
            <el-input
              v-if="queryParams.status == 4"
              v-model="queryParams.budgetMax"
              placeholder="最多预算"
              type="number"
              style="width: 120px"
            />
          </el-form-item>
          <!-- <el-form-item label="空间" prop="name">
            <el-select
              v-model="queryParams.space"
              placeholder="请选择"
              :multiple="true"
              style="width: 200px"
            >
              <el-option v-for="item in RequirementSpace" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <Search />
              </template>
              搜索
            </el-button>
            <el-button @click="handleResetQuery">
              <template #icon>
                <Refresh />
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="queryParams.status" class="enter-tabs" @tab-change="handleTabClick">
        <el-tab-pane
          v-for="item in tabList"
          :key="item.name"
          :label="item.label"
          :name="item.name"
        ></el-tab-pane>
      </el-tabs>
      <base-page-table
        :table-data="tableData"
        :table-columns-data="tableColumnsData"
        :loading="loading"
        :page-num="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        @handleQuery="handleQuery"
      >
        <template #index="scope">
          {{ scope.index + 1 }}
        </template>
        <template #handle="scope">
          <!-- 公司才有分配对接人 -->
          <!-- <el-button
            :disabled="scope.row.ChatUserStatus == 0"
            link
            type="success"
            @click="handleAttention(scope.row)"
          >
            分配对接人
          </el-button> -->
          <!-- <el-button link type="primary" @click="handleHello(scope.row)">打招呼</el-button> -->
          <!-- <el-button
            link
            type="success"
            :disabled="scope.row.relationshipMapEnable == false"
            @click="handleAtlas(scope.row)"
          >
            关系图谱
          </el-button> -->
          <el-button link type="primary" @click="lookDetail(scope.row)">查看</el-button>
        </template>
      </base-page-table>

      <AssignForm ref="assignForm" @load-data="getPaymentList"></AssignForm>
    </template>
    <template v-else>
      <atlasForm :id="opportunityId" :source="source" @backTo="handleBackTo"></atlasForm>
    </template>
    <greetForm ref="greetFormRef"></greetForm>
    <detailForm ref="detailFormRef" @nextBut="clickBut"></detailForm>
  </div>
</template>
<script setup>
import { UserTypeEnum } from "@/enums/system/UserEnum";
import OpportunityPaymentAPI from "@/api/opportunityPayment";
import router from "@/router/index.js";
import AssignForm from "@/views/opportunityPayment/components/assign-form.vue";
import atlasForm from "./components/atlas-form.vue";
import greetForm from "./components/greet-form.vue";
import detailForm from "./components/detail-form.vue";
import { useUserStore } from "@/store";
import { useDictStore } from "@/store/modules/dict";

const userInfo = useUserStore().userInfo;
const showPage = ref(true);
const columnsData = ref([
  {
    type: "index",
    label: "序号",
    width: 60,
    align: "center",
    showType: -1,
    customSlot: "index",
  },

  {
    label: "地区",
    prop: "region",
    align: "center",
    showOverflowTooltip: true,
    showType: -1,
  },
  {
    label: "小区名称",
    prop: "neighborhood",
    align: "center",
    showOverflowTooltip: true,
    showType: -1,
  },
  {
    width: 150,
    label: "业主姓名",
    prop: "ownName",
    align: "center",
    showOverflowTooltip: true,
    showType: -1,
  },
  {
    label: "联系电话",
    prop: "mobile",
    align: "center",
    showOverflowTooltip: true,
    showType: -1,
  },
  {
    label: "面积",
    prop: "size",
    align: "center",
    showOverflowTooltip: true,
    showType: -1,
  },
  {
    width: 120,
    label: "品类",
    prop: "categoryName",
    align: "center",
    showOverflowTooltip: true,
    showType: 4,
  },
  {
    width: 120,
    label: "商品数量",
    prop: "productTypeCount",
    align: "center",
    showOverflowTooltip: true,
    showType: 4,
  },
  {
    width: 200,
    label: "采买时间",
    prop: "purchaseTypeName",
    align: "center",
    showOverflowTooltip: true,
    showType: 4,
  },
  {
    width: 150,
    label: "预算（元）",
    prop: "budget",
    align: "center",
    showOverflowTooltip: true,
    showType: 4,
  },
  {
    width: 150,
    label: "对接人",
    prop: "chatUserName",
    align: "center",
    showOverflowTooltip: true,
  },

  {
    width: 200,
    label: "发布时间",
    prop: "publishTime",
    align: "center",
    showOverflowTooltip: true,
    showType: 4,
  },
  {
    width: 200,
    label: "创建时间",
    prop: "createTime",
    align: "center",
    showOverflowTooltip: true,
    showType: 4,
  },
  {
    width: 200,
    label: "操作",
    prop: "handle",
    fixed: "right",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "handle",
  },
]);
const detailInfo = ref();
const tableColumnsData = ref();
const dictStore = useDictStore();
const RequirementSpace = dictStore.getDictionary("RequirementSpace");

const defaulSource = {
  [UserTypeEnum.DESIGNER.value]: 1,
  [UserTypeEnum.DECORATION_COMPANY.value]: 1,
  [UserTypeEnum.HOME_BUILDING_MATERIALS.value]: 2,
};
const source = ref(1);
const opportunityId = ref(null);
const handleSource = () => {
  return defaulSource[userInfo?.merchantCompanyVO?.merchantUserType];
};

const tempTime = ref();
const queryFormRef = ref();
const greetFormRef = ref();
const detailFormRef = ref();
const assignForm = ref();
const loading = ref(false);
const tabList = ref([
  {
    label: "意向客户",
    name: 4,
  },
  // {
  //   label: "已领券",
  //   name: 1,
  // },
  // {
  //   label: "已失效",
  //   name: 2,
  // },
  {
    label: "成交客户",
    name: 3,
  },
]);
const handleTabClick = (val) => {
  if (queryParams.status === 4) {
    tableColumnsData.value = columnsData.value.filter((obj) => obj.showType !== 3);
  } else {
    tableColumnsData.value = columnsData.value.filter((obj) => obj.showType !== 4);
  }
  queryParams.pageNum = 1;
  getPaymentList();
};
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  startDate: "",
  endDate: "",
  status: 4,
  keyword: "",
  neighborhood: "",
  ownName: "",
  mobile: "",
  // space: [],
  budgetMax: undefined,
  budgetMin: undefined,
});

const total = ref(0);
const tableData = ref([]);
/**
 * 请求相关
 *
 */
const getPaymentList = async () => {
  try {
    loading.value = true;
    // const res = await OpportunityPaymentAPI.getRequirementPayment(queryParams);
    const res = await OpportunityPaymentAPI.getOpportunityAndRecord(queryParams);
    tableData.value = res.data;
    total.value = res.total;
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
};

function handleSearch() {
  queryParams.pageNum = 1;
  getPaymentList();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.startDate = "";
  queryParams.endDate = "";
  tempTime.value = "";
  queryParams.status = 4;
  queryParams.keyword = "";
  queryParams.neighborhood = "";
  queryParams.ownName = "";
  queryParams.mobile = "";
  // queryParams.space = [];
  queryParams.budgetMax = undefined;
  queryParams.budgetMin = undefined;
  getPaymentList();
}
function handleQuery(val) {
  queryParams.pageNum = val.pageNum;
  queryParams.pageSize = val.pageSize;
  getPaymentList();
}

function handleChange(val) {
  if (val) {
    const [startTime, endTime] = val;
    queryParams.startDate = startTime;
    queryParams.endDate = endTime;
  } else {
    queryParams.startDate = "";
    queryParams.endDate = "";
  }
}

function clickBut(val) {
  console.log(tableData.value);
  console.log(detailInfo.value.id);
  let index = tableData.value.findIndex((item) => item.id == detailInfo.value.id);
  console.log(index);

  if (val === "next") {
    const length = tableData.value.length;
    if (length === 1) {
      return ElMessage.warning("已是本页最后一单数据");
    }
    if (index >= length) {
      return ElMessage.warning("已是本页最后一单数据");
    } else {
      index++;
    }
  } else {
    if (index === 0) {
      return ElMessage.warning("已是本页第一单数据");
    } else {
      index = index - 1;
    }
  }
  detailInfo.value = tableData.value[index];
  lookDetail(detailInfo.value);
}

function lookDetail(val) {
  val["status"] = queryParams.status;
  detailInfo.value = val;
  detailFormRef.value.openModal(val);
}

async function handleGreet(val) {
  try {
    const { teamChatId } = val;
    if (teamChatId) {
      router.push({
        path: "/chat/chatList",
      });
      return;
    }
    toChat(val);
  } catch (e) {
    console.log(e);
  }
}
async function toChat(val) {
  try {
    await OpportunityPaymentAPI.toTeamChat({
      id: val.id,
      opportunitySource: val.opportunitySource,
      opportunityId: val.opportunityId,
      payUserId: val.paymentUser?.userId,
      payCompanyId: val.paymentCompanyId,
      chatUserId: val.id,
    });
    await getPaymentList();
    router.push({
      path: "/chat/chatList",
    });
  } catch (e) {
    console.log(e);
  }
}

function handleAttention(val) {
  assignForm.value.showModal(val);
}

function handleHello(row) {
  greetFormRef.value.showModal(row);
}

function handleAtlas(val) {
  opportunityId.value = val.id;
  showPage.value = false;
}

function handleBackTo() {
  showPage.value = true;
}

onMounted(() => {
  if (queryParams.status === 4) {
    tableColumnsData.value = columnsData.value.filter((obj) => obj.showType !== 3);
  } else {
    tableColumnsData.value = columnsData.value.filter((obj) => obj.showType !== 4);
  }
  //装修公司和MC02 建材MC03
  // if (userInfo.userType == "MC02") {
  //   const filts = [
  //     "requirementViewVo.purchaseTypeName",
  //     "requirementViewVo.categoryTypeName",
  //     "requirementViewVo.productTypeName",
  //   ];
  //   tableColumnsData.value = newDatas.filter((obj) => !filts.includes(obj.prop));
  // } else if (userInfo.userType == "MC03") {
  //   const filts = [
  //     "requirementViewVo.decorationFormName",
  //     "requirementViewVo.startWorkTypeName",
  //     "requirementViewVo.decorationTypeName",
  //   ];
  //   tableColumnsData.value = newDatas.filter((obj) => !filts.includes(obj.prop));
  // }
  source.value = handleSource();
  getPaymentList();
});
</script>
<style lang="scss" scoped>
.enter-tabs {
  background-color: #fff;
  padding: 10px 20px;
}
</style>
